from conan import ConanFile,tools
from conan.tools.env import VirtualBuildEnv,Environment
from conan.tools.microsoft.subsystems import unix_path
from conan.tools.files import copy
import os
import shutil

class ErpcgenConan(ConanFile):
    name = "erpcgen"
    version = "1.7.3-patch"
    # Optional metadata
    license = "BSD-2-Clause"
    author = "guyadong 10km0811@sohu.com"
    url = "https://gitee.com/l0km/erpcex"
    description = "erpcgen base NXP Embedded RPC"
    topics = ("embedded","erpc","nxp","erpcgen")

    package_type = "application"
    requires = "boost/[>=1.69.0]"
    # Binary configuration
    settings = "os", "arch"
    
    # Sources are located in the same place as this recipe, copy them to the recipe
    exports_sources = "erpc/*"

    # 获取 C++编译器位置
    # 基于 boost的conanfile.py中的_cxx 方法剪裁
    # https://github.com/conan-io/conan-center-index/blob/master/recipes/boost/all/conanfile.py
    @property
    def _cxx(self):
        compilers_by_conf = self.conf.get("tools.build:compiler_executables", default={}, check_type=dict)
        cxx = compilers_by_conf.get("cpp") or VirtualBuildEnv(self).vars().get("CXX")
        if cxx:
            return cxx
        compiler_version = str(self.settings_build.compiler.version)
        major = compiler_version.split(".", maxsplit=1)[0]
        if self.settings_build.compiler == "gcc":
            return shutil.which(f"g++-{compiler_version}") or shutil.which(f"g++-{major}") or shutil.which("g++") or ""
        return ""

    def config_options(self):
        if not self.settings_build.compiler == "gcc":
            # 只支持gcc编译,报错退出
            raise Exception("Only support gcc,plese use MinGw compiler for Windows")

    def build_requirements(self):
        if self.settings_build.os == "Windows":
            self.tool_requires("winflexbison/2.5.24")
            self.win_bash = True
            if not self.conf.get("tools.microsoft.bash:path", check_type=str):
                # Windows下需要在MSYS2环境编译
                self.tool_requires("msys2/cci.latest")

        else:
            self.tool_requires("flex/2.6.4")
            self.tool_requires("bison/3.7.6")


    def generate(self):
        # tc = AutotoolsToolchain(self)
        # env = tc.environment()
        # buildenv = VirtualBuildEnv(self)
        env = Environment()
        if self.settings_build.os == "Windows":
            # erpcgen中使用环境变量FLEX定义flex,BISON定义bison,
            # 与winflexbison加载时定义的变量名不一样,所以这里要
            # 定义环境变量 FLEX=$LEX,BISON=$YACC
            env.define('FLEX',self.dependencies.build["winflexbison"].buildenv_info.vars(self).get("LEX"))
            env.define('BISON',self.dependencies.build["winflexbison"].buildenv_info.vars(self).get("YACC"))
            include_path = unix_path(self,os.path.join(self.dependencies.build["winflexbison"].package_folder, "include"))
            # 使用外部定义的C++编译器，避免使用msys2内置的编译器，否则会因为编译版本不一致导致连接错误
            env.define('CXX',unix_path(self,self._cxx))

        else:
            # 定义环境变量 FLEX=$LEX,BISON=$BISON_ROOT/bin/bison
            env.define('FLEX',os.path.join(self.dependencies.build["flex"].package_folder,"bin", "flex"))
            env.define('BISON',self.dependencies.build["bison"].buildenv_info.vars(self).get("CONAN_BISON_ROOT") + "/bin/bison")
            include_path = os.path.join(self.dependencies.build["flex"].package_folder, "include")

        # 将 flex的include文件夹添加到INCLUDES环境变量，参见 erpc/erpcgen/Makefile中INCLUDES变量
        env.append('INCLUDES',include_path)
        # 指定boost位置
        boost_root = unix_path(self,self.dependencies["boost"].package_folder)    
        env.define('BOOST_ROOT',boost_root)
        env.append('LDFLAGS',"-L" + os.path.join(boost_root,"lib"))
        envvars = env.vars(self)
        envvars.save_script("my_env")
        # buildenv.generate()
        # tc.generate(env)
        # 输出环境变量
        self.output.info("Environment Variables:")
        for name, value in envvars.items():
            self.output.info(f"{name}={value}")

    def package(self):
        # autotools = Autotools(self)
        # # VERBOSE=1 输出详细编译信息
        # autotools.install(args=["-C", "erpc/erpcgen","VERBOSE=0", "PREFIX={}".format(unix_path(self,self.package_folder))])
        
        # VERBOSE=1 编译时输出命令
        self.run(f"VERBOSE=0 make -C erpc/erpcgen install PREFIX={unix_path(self,self.package_folder)}")

        if self.settings_build.os == "Windows":
            # 复制 erpcgen.exe 的依赖库到bin
            _cxx_bin = os.path.dirname(self._cxx);
            _dst = os.path.join(self.package_folder,"bin");
            copy(self,"libgcc*.dll",_cxx_bin,_dst)
            copy(self,"libwinpthread*.dll",_cxx_bin,_dst)
            copy(self,"libstdc++*.dll",_cxx_bin,_dst)
